package echo.nio;

import io.netty.channel.ServerChannel;
import lombok.SneakyThrows;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.nio.charset.StandardCharsets;
import java.util.Iterator;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author： zhangnan
 * @date： 2025/4/29 17:25
 * @description： TODO
 * @modifiedBy：
 * @version: 1.0
 */
public class TestNio {

    public static void main(String[] args) {
        try {
            ServerSocketChannel ssc = ServerSocketChannel.open();
            ssc.configureBlocking(false);
            ssc.bind(new InetSocketAddress(8080));
            Selector boss = Selector.open();
            ssc.register(boss,SelectionKey.OP_ACCEPT);
            Worker[] workers = new Worker[Runtime.getRuntime().availableProcessors()];
            for (int i =0;i < workers.length;i++){
                workers[i] = new Worker("worker-" + i);
            }
            AtomicInteger index = new AtomicInteger();
            while (true) {
                boss.select();
                Iterator<SelectionKey> iter = boss.selectedKeys().iterator();
                while (iter.hasNext()) {
                    SelectionKey key = iter.next();
                    iter.remove();
                    if (key.isAcceptable()) {
                        SocketChannel sc = ssc.accept();
                        sc.configureBlocking(false);
                        workers[index.getAndIncrement() % workers.length].register(sc);
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    static class Worker implements Runnable {
        private String name;
        private Thread thread;
        private Selector selector;
        private volatile boolean start = false;
        public Worker(String name) {
            this.name = name;
        }

        public void register(SocketChannel sc) throws IOException {
            if (!start) {
                this.selector = Selector.open();
                this.thread = new Thread(this,name);
                thread.start();
                start = true;
            }
            selector.wakeup();
            sc.register(selector,SelectionKey.OP_READ);
        }

        @SneakyThrows
        @Override
        public void run() {
            while (true) {
                selector.select();
                Iterator<SelectionKey> iter = selector.selectedKeys().iterator();
                while (iter.hasNext()) {
                    SelectionKey key = iter.next();
                    iter.remove();
                    if (key.isReadable()) {
                        ByteBuffer buffer = ByteBuffer.allocate(16);
                        SocketChannel channel = (SocketChannel) key.channel();
                        channel.read(buffer);
                        buffer.flip();
                        System.out.println(StandardCharsets.UTF_8.decode(buffer));
                    }
                }
            }
        }
    }

}
